package com.aigc.txt2img.service.impl;

import com.aigc.txt2img.dao.TaskMapper;
import com.aigc.txt2img.entity.CreateImageReques;
import com.aigc.txt2img.entity.Task;
import com.aigc.txt2img.service.ChatService;
import com.aigc.txt2img.third_party.net_ease.AiDraw;
import com.aigc.txt2img.third_party.net_ease.CreateImageParams;
import com.aigc.txt2img.utils.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service("chatService")
public class ChatServiceImpl implements ChatService {

    @Autowired
    private TaskMapper taskMapper;

    public String createImage(CreateImageReques createImage) throws Exception {

        CreateImageParams curlParams = new CreateImageParams();
        curlParams.setPrompt(createImage.getPrompt());
        Integer styleId= createImage.getStyleId();
        String styleName = AiDraw.getStyleName(styleId);
        curlParams.setStyleName(styleName);
        List<Integer> outputSize = new ArrayList<>();
        outputSize.add(512);
        outputSize.add(512);
        curlParams.setOutputSize(outputSize);
        String taskId =  AiDraw.CreateImage(curlParams);
        if (taskId != "") {
            Task task = new Task();
            task.setTaskId(taskId);
            task.setStatus(Task.STATUS_PENDING);
            int timestamp = TimeUtil.getCurTimestamp();
            task.setCreateTs(timestamp);
            task.setUpdateTs(timestamp);
            task.setImage("");
            int id = taskMapper.addTask(task);
            if (id < 1) {
                log.error("fail addTask task:" + task);
                return "";
            } else {
                log.info("succ addTask task:" + task);
            }
        }
        return taskId;
    }

    public String queryImage(String taskId) {

        if (taskId == "") {
            return "";
        }
        Task task = taskMapper.getByTaskID(taskId);
        log.debug("taskid:" + taskId + " task:" + task);
        if (task.getStatus() == Task.STATUS_SUCC) {
            return task.getImage();
        }
        return "";
    }

    public boolean notify(String taskId,String image) {

        if (taskId == "") {
            return false;
        }
        Task task = taskMapper.getByTaskID(taskId);
        if (task == null || task.getStatus() != Task.STATUS_PENDING) {
            return true;
        }
        task.setImage(image);
        task.setStatus(Task.STATUS_SUCC);
        task.setUpdateTs(TimeUtil.getCurTimestamp());
        if (taskMapper.updateTask(task) >0 ) {
            return true;
        }
        return false;
    }

}
